package com.thinkgem.jeesite.modules.fantasy.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.thinkgem.jeesite.modules.fantasy.service.impl.FantasyUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.fantasy.entity.Cabinet;
import com.thinkgem.jeesite.modules.fantasy.entity.CityMap;
import com.thinkgem.jeesite.modules.fantasy.entity.FantasyUser;
import com.thinkgem.jeesite.modules.fantasy.entity.FantasyUserPosition;
import com.thinkgem.jeesite.modules.fantasy.entity.ItemType;
import com.thinkgem.jeesite.modules.fantasy.entity.NPCPosition;
import com.thinkgem.jeesite.modules.fantasy.service.impl.CityMapService;
import com.thinkgem.jeesite.modules.fantasy.service.impl.ItemService;
import com.thinkgem.jeesite.modules.sys.security.Principal;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value = "fantasy/move")
public class MoveController extends BaseController {
	@Autowired
	private CityMapService cityMapService;
	private String targetid;
	private String fromid;
	@Autowired
	private ItemService itemService;
	private CityMap cityMap;
	@Autowired
	private FantasyUserService userService;

	Map<String, CityMap> cities = WorldInit.cities;
	
	Map<String, ArrayList<NPCPosition>> npcs = WorldInit.npcs;
	
	Map<String, ArrayList<FantasyUserPosition>> users = WorldInit.users;

	Map<String, ItemType[]> ranItems = WorldInit.ranItems;
    public String getTargetid() {
		return targetid;
	}

	public void setTargetid(String targetid) {
		this.targetid = targetid;
	}

	public String getFromid() {
		return fromid;
	}

	public void setFromid(String fromid) {
		/*if (fromid == null) {
			fromid = (String) session.get("homepoint");
		}*/
		this.fromid = fromid;
	}

    /*
     * 回家
     */
	@RequestMapping(value = "/tohome")
    public ModelAndView moveToHome(HttpServletRequest request) {
    	logger.debug("moveToHome()");
    	ModelAndView mv = new ModelAndView();
    	Principal principal = UserUtils.getPrincipal();
    	if(principal != null) {
    		Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			FantasyUser user = (FantasyUser) session.getAttribute("operator");
			if (null == user) {
				logger.error("user == null");
				mv.setViewName("error/500");
				return mv;
			}
			mv.addObject("user", user);
    		fromid = (String) request.getAttribute("fromid");
    		targetid = user.getHomePoint();
    		//第一次登陆时初始化fromid
    		fromid = targetid;
    		//点击回家时，更新lastpoint值为家所在节点，否则从家里点击上街后会到达lastpoint之前指定的节点位置。
    		session.setAttribute("lastpoint", targetid);
    		//区分在家还是在街道上
    		session.setAttribute("whereami", "home");
    		//更新用户位置信息
    		updateUserPosition();
    		//获取用户家中的柜子列表
    		List<Cabinet> cabinets = itemService.getCabinetsByUserid(user.getId());
    		System.out.println("cabinets == " + cabinets.size());
    		mv.addObject("cabinets", cabinets);
    		mv.setViewName("modules/fantasy/home");
			//修改用户的所在城市
			userService.moveUser(user, user.getHomePoint());
    	} else {
    		mv.setViewName("error/500");
    	}
		return mv;
    }
	/*
     * 上街
     */
	@RequestMapping(value = "/moveToStreets")
    public ModelAndView moveToStreets(HttpServletRequest request) {
    	logger.debug("moveToStreets()");
    	ModelAndView mv = new ModelAndView();
    	Principal principal = UserUtils.getPrincipal();
    	if(principal != null) {
    		Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			FantasyUser user = (FantasyUser) session.getAttribute("operator");
			if (null == user) {
				logger.error("user == null");
				mv.setViewName("error/500");
				return mv;
			}
			mv.addObject("user", user);
			
			String homePoint = user.getHomePoint();
			cityMap = cityMapService.getCityMapById(homePoint);
			mv.addObject("cityMap", cityMap);
			mv.addObject("targetid", homePoint);
			//区分在家还是在街道上
			session.setAttribute("whereami", "street");
			mv.addObject("fromid", homePoint);
    		
    		//更新用户位置信息
    		//updateUserPosition();
    		mv.setViewName("modules/fantasy/main");
    	} else {
    		mv.setViewName("error/500");
    	}
		return mv;
    }

    /*
     * 在地图上移动
     */
	@RequestMapping(value = "/moveTo")
    public ModelAndView moveTo(HttpServletRequest request) {
    	logger.debug("moveTo()");
		targetid = (String) request.getParameter("targetid");
		fromid = (String) request.getParameter("fromid");
		logger.debug("targetid == " + targetid);
		logger.debug("fromid == " + fromid);
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("targetid", targetid);
		mv.addObject("fromid", fromid);
		
    	Principal principal = UserUtils.getPrincipal();
    	if(principal != null) {
    		Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			FantasyUser user = (FantasyUser) session.getAttribute("operator");
			if (null == user) {
				logger.error("user == null");
				mv.setViewName("error/500");
				return mv;
			}
			mv.addObject("user", user);

    		//获取前一页面mapid
    		String referer = (String) request.getHeader("Referer");
    		logger.debug("referer == {}", referer);
    		if (referer == null) {
    			logger.debug("当前路径错误");
    			mv.addObject("message", "当前路径错误");
				mv.setViewName("error/500");
				return mv;
    		}
    		
    		cityMap = cities.get(targetid);
    		if (cityMap == null) {
    			cityMap = cityMapService.getCityMapById(targetid);
    		}
    		
    		ArrayList<NPCPosition> npclist = npcs.get(targetid);
    		
    		//更新用户位置信息
    		ArrayList<FantasyUserPosition> userlist = updateUserPosition();
    		
    		ItemType[] itemList = ranItems.get(targetid);
    		if (itemList != null) {
    			System.out.println(itemList.length);
    		}
    		
    		//更新session中的最近坐标值，供强制刷新时使用。
    		session.setAttribute("lastpoint", targetid);

    		mv.addObject("cityMap", cityMap);
    		mv.addObject("npclist", npclist);
    		mv.addObject("userlist", userlist);
    		mv.addObject("itemList", itemList);
    		mv.setViewName("modules/fantasy/movetotarget");

			//修改用户的所在城市
			userService.moveUser(user, targetid);
    		return mv;
    	}
		mv.setViewName("error/500");
		return mv;
    }
    
    public ArrayList<FantasyUserPosition> updateUserPosition(){
    	//删除当前节点下用户位置信息
    	Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		FantasyUser user = (FantasyUser) session.getAttribute("operator");
		FantasyUserPosition nup = null;
		logger.debug("from ---");
    	//删除原节点下用户位置信息
		if (users.get(fromid) != null) {
			List<FantasyUserPosition> ups = users.get(fromid);
			logger.debug("from处人数  == " + ups.size());
			for (FantasyUserPosition up : ups) {
				if (up.getUserid().equals(user.getId())) {
					logger.debug("from处发现：" + up.getName());
					nup = up;
					ups.remove(up);
					logger.debug("from处移除：" + up.getName());
					break;
				}
			}
			logger.debug("from处移动后人数 == " + ups.size());
		}
		//F5或强制刷新当前页面时，会导致当前页面自己的数量增多
		logger.debug("target ---");
    	//如果是刷新操作，目标节点下会有用户位置信息，所以要先进行删除
		if (users.get(targetid) != null) {
			List<FantasyUserPosition> ups = users.get(targetid);
			logger.debug("target处人数  == " + ups.size());
			for (FantasyUserPosition up : ups) {
				if (up.getUserid().equals(user.getId())) {
					logger.debug("target处发现：" + up.getName());
					nup = up;
					ups.remove(up);
					logger.debug("target处移除：" + up.getName());
					break;
				}
			}
			logger.debug("target处移动后人数  == " + ups.size());
		}
		
		//增加目标节点下用户位置信息
		logger.debug("nup == " + nup);
		if (nup == null) {
			nup = new FantasyUserPosition();
			nup.setMapid(targetid);
			nup.setName(user.getNickname() + "(" + user.getUsername() + ")");
			nup.setUserid(user.getId());
		} else {
			nup.setMapid(targetid);
		}
		logger.debug("users.containsKey(targetid) == " + users.containsKey(targetid));
		//如果目标节点没有出现过用户，新建一个List
		if(!users.containsKey(targetid)){
			users.put(targetid, new ArrayList<FantasyUserPosition>());
		}
		users.get(targetid).add(nup);
		logger.debug("target处移动后人数 == " + users.get(targetid).size());
		
		return users.get(targetid);
	}


	@RequestMapping(value = "/toHomeLeft")
	public ModelAndView toHomeLeft(HttpServletRequest request) {
		logger.debug("toHomeLeft()");
		ModelAndView mv = new ModelAndView();
		Principal principal = UserUtils.getPrincipal();
		if(principal != null) {
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			FantasyUser user = (FantasyUser) session.getAttribute("operator");
			if (null == user) {
				logger.error("user == null");
				mv.setViewName("error/500");
				return mv;
			}
			mv.addObject("user", user);

			String homePoint = user.getHomePoint();
			cityMap = cityMapService.getCityMapById(homePoint);
			mv.addObject("cityMap", cityMap);
			mv.addObject("targetid", homePoint);
			//区分在家还是在街道上
			session.setAttribute("whereami", "home");
			mv.addObject("fromid", homePoint);

			//更新用户位置信息
			//updateUserPosition();
			mv.setViewName("modules/fantasy/homeleft");
		} else {
			mv.setViewName("error/500");
		}
		return mv;
	}

	@RequestMapping(value = "/toCompass")
	public ModelAndView toCompass(HttpServletRequest request) {
		logger.debug("toCompass()");
		ModelAndView mv = new ModelAndView();
		Principal principal = UserUtils.getPrincipal();
		if(principal != null) {
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			FantasyUser user = (FantasyUser) session.getAttribute("operator");
			if (null == user) {
				logger.error("user == null");
				mv.setViewName("error/500");
				return mv;
			}
			mv.addObject("user", user);

			String homePoint = user.getHomePoint();
			cityMap = cityMapService.getCityMapById(homePoint);
			mv.addObject("cityMap", cityMap);
			mv.addObject("targetid", homePoint);
			//区分在家还是在街道上
			session.setAttribute("whereami", "street");
			mv.addObject("fromid", homePoint);

			//更新用户位置信息
			//updateUserPosition();
			mv.setViewName("modules/fantasy/compass");
		} else {
			mv.setViewName("error/500");
		}
		return mv;
	}


	@RequestMapping(value = "/toHomeMain")
	public ModelAndView toHomeMain(HttpServletRequest request) {
		logger.debug("toHomeMain()");
		ModelAndView mv = new ModelAndView();
		Principal principal = UserUtils.getPrincipal();
		if(principal != null) {
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			FantasyUser user = (FantasyUser) session.getAttribute("operator");
			if (null == user) {
				logger.error("user == null");
				mv.setViewName("error/500");
				return mv;
			}
			mv.addObject("user", user);

			String homePoint = user.getHomePoint();
			cityMap = cityMapService.getCityMapById(homePoint);
			mv.addObject("cityMap", cityMap);
			mv.addObject("targetid", homePoint);
			//区分在家还是在街道上
			session.setAttribute("whereami", "home");
			mv.addObject("fromid", homePoint);

			//更新用户位置信息
			//updateUserPosition();
			mv.setViewName("modules/fantasy/homemain");
		} else {
			mv.setViewName("error/500");
		}
		return mv;
	}
}
